package v1

import (
	"fmt"
	"gin-project/model"
	"gin-project/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

func InsertUser(ctx *gin.Context) {
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")
	sex := ctx.PostForm("sex")
	phoneNum := ctx.PostForm("phoneNum")
	email := ctx.PostForm("email")
	birth := ctx.PostForm("birth")
	introduction := ctx.PostForm("introduction")
	location := ctx.PostForm("location")
	sexInt, _ := strconv.Atoi(sex)

	var user model.User
	user.UserName = username
	user.PassWord = password
	user.Sex = sexInt
	user.Phone = phoneNum
	user.Email = email
	user.Birth = birth
	user.Introduction = introduction
	user.Location = location

	code := model.InsertUser(&user)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
	})
	return
}

func SelectUserAll(ctx *gin.Context) {
	users, code := model.SelectUserAll()
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
		"data": users,
	})
	return
}

func UpdateUserPic(ctx *gin.Context) {
	file, header, _ := ctx.Request.FormFile("file")
	id := ctx.PostForm("id")
	fmt.Println(header.Filename)
	fmt.Println(id)

	url, _ := model.UpdateUserPic(file, header)
	code := model.UpdateUser(map[string]interface{}{
		"avatar": url,
	}, id)

	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
	})
	return
}

func UpdateUser(ctx *gin.Context) {
	id := ctx.PostForm("id")
	username := ctx.PostForm("username")
	password := ctx.PostForm("password")
	sex := ctx.PostForm("sex")
	phoneNum := ctx.PostForm("phoneNum")
	email := ctx.PostForm("email")
	birth := ctx.PostForm("birth")
	introduction := ctx.PostForm("introduction")
	location := ctx.PostForm("location")
	sexInt, _ := strconv.Atoi(sex)

	code := model.UpdateUser(map[string]interface{}{
		"user_name":    username,
		"pass_word":    password,
		"sex":          sexInt,
		"phone":        phoneNum,
		"email":        email,
		"birth":        birth,
		"introduction": introduction,
		"location":     location,
	}, id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
	})
	return
}

func DeleteUserByID(ctx *gin.Context) {
	id := ctx.Query("id")

	code := model.DeleteUserByID(id)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg": errmsg.GetErrMsg(code),
	})
	return
}